package com.gxuwz.attend.web.servlet;
import com.alibaba.excel.EasyExcel;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Leave;
import com.gxuwz.attend.entity.LeaveExport;
import com.gxuwz.attend.service.Impl.LeaveServiceImpl;
import com.gxuwz.attend.tools.DateUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@WebServlet(name = "leaveServlet",urlPatterns = "/leave")
public class LeaveServlet extends BaseHttpServlet{
    private final Logger logger= LoggerFactory.getLogger(DepartmentServlet.class);
    private final static String VIEW_ADD="/WEB-INF/views/leave/leave_add.jsp";
    private final static String VIEW_EDIT="/WEB-INF/views/leave/leave_edit.jsp";
    private final static String VIEW_LIST="/WEB-INF/views/leave/leave_list.jsp";
    private final static String ACTION_LIST="/leave?action=list";
    private LeaveServiceImpl leaveService;
    @Override
    public void init() throws ServletException {
        super.init();
        leaveService = AppContext.getBean(LeaveServiceImpl.class);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("..................");
        System.out.println();
//1：接受请求参数action以及其他页面的参数值，按照约定，动作请求action依次为input、add、delete、get、edit、list.
        String action =req.getParameter("action");
        System.out.println("action:" + action);
        String view=ErrorPage_500;
        logger.info("request process starting"+action);
        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "input":
                    view = VIEW_ADD;
                    Leave leave = new Leave();
                    //leave.setLeaveID("");
                    leave.setCourseID("");
                    leave.setReason("");
                    leave.setDaynum(0);
                    leave.setStuNo("");
                    LocalDate now = LocalDate.now();
                    leave.setApplytime(now);
                    leave.setStatus("");
                    leave.setDatetime(now);
                    leave.setOpinion("");
                    req.setAttribute("leave",leave);
                    break;
                case "add":
                    leave = new Leave();
                    //resolveRequestParameter(req,leave);
                    //String leaveID=req.getParameter("leaveID");
                    LocalDateTime now1 = LocalDateTime.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    Random random = new Random();
                    int randomNumber = random.nextInt(900) + 100;
                    String leaveID = now1.format(formatter)+randomNumber;
                    String courseID=req.getParameter("courseID");
                    String reason=req.getParameter("reason");
                    String daynum=req.getParameter("daynum");
                    String stuNo=req.getParameter("stuNo");
                    String applytime=req.getParameter("applytime");
                    /*String status=req.getParameter("status");
                    String datetime=req.getParameter("datetime");
                    String opinion=req.getParameter("opinion");*/
                    leave.setLeaveID(leaveID);
                    leave.setCourseID(courseID);
                    leave.setReason(reason);
                    leave.setDaynum(Integer.valueOf(daynum));
                    leave.setStuNo(stuNo);
                    leave.setApplytime(LocalDate.parse(applytime));
                    /*leave.setStatus(status);
                    leave.setDatetime(LocalDate.parse(datetime));
                    leave.setOpinion(opinion);*/
                    System.out.println("leaveID:"+leaveID);
                    System.out.println("add-leave:"+leave);
                    leaveService.insertLeave(leave);
                    //指定跳转路径
                    view = ACTION_LIST;
                    break;
                case "delete":
                    String id =req.getParameter("id");
                    System.out.println("delete-leaveID:"+id);
                    leaveService.deleteLeave(id);
                    view = ACTION_LIST;
                    break;
                case "get":
                    id =req.getParameter("id");
                    leave = new Leave();
                    leave.setLeaveID(id);
                    System.out.println("get-leaveID:" +id);
                    List<Leave> leaveList = new ArrayList<>();
                    leaveList = leaveService.queryLeave(leave);
                    leave = leaveList.get(0);
                    view = VIEW_EDIT;
                    req.setAttribute("m",leave);
                    break;
                case "edit":
                    leave = new Leave();
                    //resolveRequestParameter(req,leave);
                    String leaveID1=req.getParameter("leaveID");
                    String courseID1=req.getParameter("courseID");
                    String reason1=req.getParameter("reason");
                    String daynum1=req.getParameter("daynum");
                    String stuNo1=req.getParameter("stuNo");
/*                    String applytime1=req.getParameter("applytime");
                    String status1=req.getParameter("status");
                    String datetime1=req.getParameter("datetime");
                    String opinion1=req.getParameter("opinion");*/
                    leave.setLeaveID(leaveID1);
                    leave.setCourseID(courseID1);
                    leave.setReason(reason1);
                    leave.setDaynum(Integer.valueOf(daynum1));
                    leave.setStuNo(stuNo1);
                   /* leave.setApplytime(LocalDate.parse(applytime1));
                    leave.setStatus(status1);
                    leave.setDatetime(LocalDate.parse(datetime1));
                    leave.setOpinion(opinion1);*/

                    System.out.println("leaveID:"+leaveID1);
                    System.out.println("edit-leave:"+leave);
                    leaveService.updateLeave(leave);
                    view = ACTION_LIST;
                    break;
                case "export":
                    List<LeaveExport> leaveDataList = new ArrayList<>();
                    List<Leave> leaveDataList1 = new ArrayList<>();
                    leaveDataList1 = leaveService.queryLeaves();
                    for(Leave leave7:leaveDataList1){
                        LeaveExport leaveExport = new LeaveExport();
                        String leaveID7=leave7.getLeaveID();
                        String courseID7=leave7.getCourseID();
                        String reason7=leave7.getReason();
                        int daynum7=leave7.getDaynum();
                        String stuNo7=leave7.getStuNo();
                        String applytime7 = DateUtil.format(leave7.getApplytime());
                        String status7=leave7.getStatus();
                        String dateTime7= DateUtil.format(leave7.getDatetime());
                        String opinion7=leave7.getOpinion();
                        leaveExport.setLeaveID(leaveID7);
                        leaveExport.setCourseID(courseID7);
                        leaveExport.setReason(reason7);
                        leaveExport.setDaynum(Integer.valueOf(daynum7));
                        leaveExport.setStuNo(stuNo7);
                        leaveExport.setApplytime(applytime7);
                        leaveExport.setStatus(status7);
                        leaveExport.setDatetime(dateTime7);
                        leaveExport.setOpinion(opinion7);
                        leaveDataList.add(leaveExport);
                    }

                    // 设置响应头
                    resp.setContentType("application/vnd.ms-excel");
                    resp.setHeader("Content-Disposition", "attachment;filename=leaves.xlsx");

                    // 导出Excel文件到浏览器
                    try (ServletOutputStream outputStream = resp.getOutputStream()) {
                        EasyExcel.write(outputStream, LeaveExport.class).sheet("请假信息").doWrite(leaveDataList);
                        System.out.println("导出成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                        req.setAttribute("message", e.getMessage());
                        view = ErrorPage_500;
                    }
                    break;
                case "list":
                    System.out.println(11);
                    String stuNo2=req.getParameter("stuNo11");
                    System.out.println("stuNo:"+stuNo2);
                    if (stuNo2==null||stuNo2.isEmpty()){
                        List<Leave> leaveList1 = new ArrayList<>();
                        leaveList1 = leaveService.queryLeaves();
                        view = VIEW_LIST;
                        req.setAttribute("list",leaveList1);
                        break;
                    }else{
                        Leave leave1 = new Leave();
                        leave1.setStuNo(stuNo2);
                        List<Leave> leaveList1 = new ArrayList<>();
                        leaveList1 = leaveService.queryLeave(leave1);
                        view = VIEW_LIST;
                        req.setAttribute("list",leaveList1);
                        break;
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("message",e.getMessage());
            view =ErrorPage_500;
        }
        //3:页面跳转，默认转发方式
        super.doDispatch(req,resp,view);
    }

    /**
     * 解析request参数并转换为POJO对象
     * @param req
     */
    private void resolveRequestParameter(HttpServletRequest req,Object bean){
        Map<String,String[]> reqParameterMap= req.getParameterMap();
        Map<String,String[]> propertiesMap=new HashMap<String,String[]>();
        try {
            for (Map.Entry<String,String[]>  entry : reqParameterMap.entrySet()){
                String name =entry.getKey();
                String[] values=entry.getValue();
                //判断request参数是否对应JavaBean对象的属性
                Class propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType!=null) {
                    propertiesMap.put(name,values);
                }
            }
            //转换为POJO对象bean的属性值
            BeanUtils.populate(bean,propertiesMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("The property name could not be found",e);
        }
    }

}
